<?php

namespace App\Http\Controllers\Api\V1;

use Carbon\Carbon;
use App\Models\User;
use App\Models\Statistic;
use App\Models\SeckillProduct;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Cache;
use App\Services\MakeSeckillOrder\MakeSeckillOrderRequest;
use App\Services\MakeProductOrder\MakeProductOrder;
use App\Http\Controllers\Api\V1\Resources\OrderResource;
use App\Http\Controllers\Api\V1\Resources\SeckillProductResource;
use App\Http\Controllers\Api\V1\Resources\SeckillProductItemResource;


class SeckillProductsController extends Controller
{
	
	

	public function index()
	{
		$source = request('source');
		$keyword = request('keyword');
		$products = SeckillProduct::getProducts($source,$keyword);

		return SeckillProductResource::collection($products);

		//return response()->json($products);
	}


	public function show($id)
	{
		
		$product = SeckillProduct::find($id);
		return new SeckillProductItemResource($product);
	}


	public function info()
	{
		$strat_at = cs("sale")->start_at;
		$end_at = cs("sale")->end_at;


		$result = [
			'seckill_range_time' => $strat_at."-".$end_at,
			'today_start_at' =>  date("Y-m-d",time()).' '.$strat_at,
			'today_end_at' => date("Y-m-d",time()).' '.$end_at,

		];
		if(Carbon::now()->lt($result['today_start_at'])){

			$result['status'] = 'waiting';
		}elseif(Carbon::now()->gt($result['today_end_at'])){

			$result['status'] = 'ending';
		}else{

			$result['status'] = 'running';
		}

		return response()->json($result);
	}


	
	public function store()
	{
		$lock = Cache::lock('buy_seckill_product', 15);

		try {

			if (! $lock->get()) fail('高峰拥挤，请再试');

			$request = app(MakeSeckillOrderRequest::class);
			$uid = $request->user()->id;
			$sid = $request->sid;
			$skuId = $request->sku_id;

			$order = app(MakeProductOrder::class, [
			    'user' => $request->user(),
			    'address' => $request->getAddress(),
			    'items' => $request->items(),
			    'sid' => $sid,
		    ])->make();

           return new OrderResource($order);

		} finally {
			$lock->release();
		}
	}

	

	

	
}
